package com.pactera.config.security;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import com.pactera.model.SysUser;
import com.pactera.service.system.SysUserService;

@Component
public class SelfUserDetailsService implements UserDetailsService {

    private Logger logger = LoggerFactory.getLogger(getClass());
    
    @Autowired
	private SysUserService sysUserService;
    
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        logger.info("用户的用户名: {}", username);
        
        //根据登录用户名查询用户信息
        SysUser sysUser = sysUserService.getByAccount(username);
        
        if(sysUser == null){
        	throw new UsernameNotFoundException(username + " do not exist!");
        } 
        
        //用户权限集合
        //AuthorityUtils.commaSeparatedStringToAuthorityList("admin")
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        if(username.equals("admin")){
        	authorities.add(new SimpleGrantedAuthority("admin"));
        }
        
        // 封装用户信息(用户名,密码,权限)
        User user = new User(username, sysUser.getPassword(),authorities);
        if (!user.isEnabled()){  
        	logger.info("用户已被禁用");
            throw new DisabledException("用户已被禁用");  
        }else if (!user.isAccountNonExpired()) {  
            logger.info("账号已过期");
            throw new LockedException("账号已过期");  
        }else if (!user.isAccountNonLocked()) {  
            logger.info("账号已被锁定");
            throw new LockedException("账号已被锁定");  
        }else if (!user.isCredentialsNonExpired()) {  
            logger.info("凭证已过期");
            throw new LockedException("凭证已过期");  
        }  
        return user;
  }
}
